package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisWorker {

    private final static long BEGIN_TIMESTAMP = 1742661452L;

    private final static long COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPerfix) {

        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        // 将当前的时间，转换为秒
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 计算与初始时间的差值
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        // 2.生成自增序列化（利用redis）
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPerfix + ":" + date);

        return timestamp << COUNT_BITS | count;
    }
}
